package com.hsq.ndmall.wx.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.hsq.ndmall.common.holder.LoginUserHolder;
import com.hsq.ndmall.common.utils.ListFromEntity2VoUtils;
import com.hsq.ndmall.common.utils.R;
import com.hsq.ndmall.common.utils.WxResponseCode;
import com.hsq.ndmall.wx.feign.goods.GoodsDetailFeign;
import com.hsq.ndmall.wx.feign.order.MallFeign;
import com.hsq.ndmall.wx.feign.order.OrderFeign;
import com.hsq.ndmall.wx.feign.order.PromotionFeign;
import com.hsq.ndmall.wx.feign.order.UserFeign;
import com.hsq.ndmall.wx.from.CheckoutFrom;
import com.hsq.ndmall.wx.from.FastAddFrom;
import com.hsq.ndmall.wx.vo.goods.GoodsProductVo;
import com.hsq.ndmall.wx.vo.groupon.GrouponRulesVo;
import com.hsq.ndmall.wx.vo.order.CartVo;
import com.hsq.ndmall.wx.vo.promotion.CouponHomeVo;
import com.hsq.ndmall.wx.vo.ums.AddressVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hsq.ndmall.common.utils.WxResponseCode.GOODS_NO_STOCK;

/**
 * @author 黄四清
 * @version 1.0.0
 * @ClassName CartService.java
 * @Description TODO 立即购买
 * @createTime 2021年08月19日 16:12:00
 */
@Service
public class CartService {

    @Autowired
    GoodsDetailFeign goodsDetailFeign;

    @Autowired
    OrderFeign orderFeign;

    @Autowired
    UserFeign userFeign;

    @Autowired
    PromotionFeign promotionFeign;

    @Autowired
    MallFeign mallFeign;

    @Autowired
    LoginUserHolder loginUserHolder;

    public Map isFastAdd(Integer userId, FastAddFrom fastAddFrom) {
        Map<String, Object> paramMap = new HashMap<>();
        System.out.println(userId + "=====================3");
        Map resultMap = new HashMap();
        if (userId == null) {
            // 没有参数
            resultMap.put("errno", "501");
            resultMap.put("errmsg", "请登录");
            return resultMap;
        }
        if (fastAddFrom.getNumber() == null || fastAddFrom.getGoodsId() == null || fastAddFrom.getProductId() == null) {
            // 参数不对
            resultMap.put("errno", "402");
            resultMap.put("errmsg", "参数不对");
            return resultMap;
        }
        //  1、商品数量是否大于零
        if (fastAddFrom.getNumber() < 1) {
            resultMap.put("errno", "402");
            resultMap.put("errmsg", "参数不对");
        }
        // 2、查询商品信息,拿到商品信息
        R goodsR = goodsDetailFeign.info(fastAddFrom.getGoodsId());
        Map goodsMap = (Map) goodsR.get("goods");
        //  3、是否上下架
        if (goodsR == null || ((Integer) goodsMap.get("isOnSale")) == 0) {
            resultMap.put("errno", WxResponseCode.GOODS_UNSHELVE.getCode());
            resultMap.put("errmsg", WxResponseCode.GOODS_UNSHELVE.getMsg());
            return resultMap;
        }
        // 4、查询产品信息
        paramMap.put("id", fastAddFrom.getProductId());
        R productListR = goodsDetailFeign.goodsProductList(paramMap);
        List<Map> productList = (List<Map>) ((Map) productListR.get("page")).get("list");
        List<GoodsProductVo> goodsProductVoList = ListFromEntity2VoUtils.entity2Vo(productList, GoodsProductVo.class);
        // 5、查询购物车是否存在
        paramMap.clear();
        paramMap.put("goods_id", fastAddFrom.getGoodsId());
        paramMap.put("product_id", fastAddFrom.getProductId());
        paramMap.put("user_id", userId);
        paramMap.put("price", goodsProductVoList.get(0).getPrice());
        // 得到购物车包含
        R cartListR = orderFeign.list(paramMap);
        List<Map> existCartMap = MapUtil.get((Map) cartListR.get("page"), "list", List.class);
        List<CartVo> cartAddForms = ListFromEntity2VoUtils.entity2Vo(existCartMap, CartVo.class);
        CartVo existCart = cartAddForms.size() == 0 ? null : cartAddForms.get(0);
        Integer newCartId = null;
        CartVo cartVo = new CartVo();  // 定义购物车实体类
        if (existCart == null) {
            //取得规格的信息,判断规格库存
            if (productListR == null || fastAddFrom.getNumber() > (Integer) (productList.get(0).get("number"))) {
                return R.error(GOODS_NO_STOCK.getCode(), "库存不足");
            }

            cartVo.setId(null);  // 购物车ID，主键自增
            cartVo.setNumber(fastAddFrom.getNumber()); // 数量
            cartVo.setGoodsId(fastAddFrom.getGoodsId());  // 商品ID信息
            cartVo.setGoodsName((String) goodsMap.get("name"));  // 商品名字
            cartVo.setProductId(fastAddFrom.getProductId());  // 规则ID
            cartVo.setGoodsSn((String) goodsMap.get("goodsSn"));// 商品编号
            cartVo.setUserId(userId);// 用户ID
            cartVo.setPrice(goodsProductVoList.get(0).getPrice());  // 价格
            if (goodsProductVoList.get(0).getUrl() == null) {
                // 如果规格图片为空，则设计商品的图片
                cartVo.setPicUrl((String) goodsMap.get("picUrl"));
            } else {
                cartVo.setPicUrl(goodsProductVoList.get(0).getUrl());
            }
            // TODO 有个BUG,需要把字符数组转为json字符数组
            cartVo.setSpecifications(goodsProductVoList.get(0).getSpecifications());  // 规格
            //System.out.println(JSONUtil.parseArray(goodsProductVoList.get(0).getSpecifications()).toString() + "=========我正在测试！");
            cartVo.setChecked(true);

            //  添加到购物车数据库中
            R save = orderFeign.save(cartVo);
            newCartId = (Integer) (save.get("data"));

        } else {
            // TODO 购物车有
            //计算商品规格信息的库存
            if (fastAddFrom.getNumber() > goodsProductVoList.get(0).getNumber()) {
                return R.error(GOODS_NO_STOCK.getCode(), "库存不足");
            }
            cartVo.setId(existCart.getId());
            cartVo.setNumber(fastAddFrom.getNumber());
            // 更新购物车的数量
            R update = orderFeign.update(cartVo);
            resultMap.put("data", (Integer) (update.get("data")));
            return resultMap;
        }
        resultMap.put("data", newCartId);
        return resultMap;
    }


    public Map isCheckout(Integer id, CheckoutFrom checkoutFrom) {
        Map resultMap = new HashMap();
        Map paramMap = new HashMap<String, Object>();
        // TODO 1.判断用户是否登录
        if (id == null) {
            resultMap.put("errno", "401");
            resultMap.put("errmsg", "请登录");
            return resultMap;
        }

        //TODO 2.是否有收获地址
        AddressVo addressVo = new AddressVo();
        //如果用户传入addressID为空，则去查询这个用户是否有默认地址
        if (checkoutFrom.getAddressId() == null || checkoutFrom.getAddressId().equals(0)) {
            paramMap.put("user_id", id);
            paramMap.put("is_default", 1);
            // 拿到用户的默认地址
            R addressR = userFeign.addresslist(paramMap);
            List<Map> addressList = (List<Map>) ((Map) addressR.get("page")).get("list");
            if (addressList.size() > 0) {
                //addressVo  = BeanUtil.mapToBean(addressList.get(0), AddressVo.class,false);
                List<AddressVo> addressVos = ListFromEntity2VoUtils.entity2Vo(addressList, AddressVo.class);
                addressVo = addressVos.get(0);
                // 设置地址
                checkoutFrom.setAddressId(addressVo.getId());
            } else {
                // 如果仍然没有地址，则是没有收货地址
                // 返回一个空的地址id=0，这样前端则会提醒添加地址
                checkoutFrom.setAddressId(0);
            }
        } else {
            // 用户传入有地址，去查询
            paramMap.clear(); // 清空map集合
            paramMap.put("id", checkoutFrom.getAddressId());
            // 查询地址信息
            R addressR = userFeign.addresslist(paramMap);
            List<Map> addressList = (List<Map>) ((Map) addressR.get("page")).get("list");
            List<AddressVo> addressVos = ListFromEntity2VoUtils.entity2Vo(addressList, AddressVo.class);
            if (addressVos.size() > 0) {
                addressVo = addressVos.get(0);
            } else {
                resultMap.put("errno", "402");
                resultMap.put("errmsg", "你的地址信息不对！");
                return resultMap;
            }
        }
        resultMap.put("checkedAddress", addressVo);

        // TODO 3、获取团购信息
        BigDecimal grouponPrice = new BigDecimal(0.00);
        GrouponRulesVo groupOnVo = null;
        if (checkoutFrom.getGrouponRulesId() == null || checkoutFrom.getGrouponRulesId().equals(0)) {
            resultMap.put("grouponRulesVos", null);
        } else {
            R grouponInfoR = promotionFeign.grouponInfo(checkoutFrom.getGrouponRulesId());
            //Map grouponInfo = ((Map) grouponInfoR.get("grouponRules"));
            //List<GrouponRulesVo> grouponRulesVos = ListFromEntity2VoUtils.entity2Vo(grouponInfo, GrouponRulesVo.class);
            groupOnVo = MapUtil.get(grouponInfoR, "grouponRules", GrouponRulesVo.class);
            resultMap.put("grouponRulesVos", groupOnVo);
            if (groupOnVo != null) {
                grouponPrice = new BigDecimal(groupOnVo.getDiscount());
            }
        }


        // TODO 4、商品价格
        List<CartVo> checkedGoodsList = new ArrayList<>();
        if (checkoutFrom.getCartId() == null || checkoutFrom.getCartId().equals(0)) {
            paramMap.clear();
            paramMap.put("user_id", id);
            R orderList = orderFeign.list(paramMap);
        } else {
            paramMap.clear();
            paramMap.put("id", checkoutFrom.getCartId());
            R orderR = orderFeign.list(paramMap);
            List<Map> orderList = (List<Map>) (((Map) orderR.get("page")).get("list"));
            List<CartVo> cartVos = ListFromEntity2VoUtils.entity2Vo(orderList, CartVo.class);
            if (orderR == null) {
                resultMap.put("errno", "402");
                resultMap.put("errmsg", "参数信息不对");
                return resultMap;
            }
            CartVo cartVo = cartVos.get(0);
            checkedGoodsList.add(cartVo);
        }
        // 下单商品总金额
        BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
        // 遍历购物车商品信息
        for (CartVo cart : checkedGoodsList) {
            //  只有当团购规格商品ID符合才进行团购优惠
            if (groupOnVo != null && groupOnVo.getGoodsId().equals(cart.getGoodsId())) {
                // checkedGoodsPrice +=  （购物车商品的价格-团购优惠的金额） * 商品的数量
                checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().subtract(grouponPrice).multiply(new BigDecimal(cart.getNumber())));
            } else {
                // 没有团购信商品ID checkedGoodsPrice += （购物车商品的价格 * 商品的数量）
                checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        }
        // 计算优惠券可用情况
        // 根据用户Id查询所有优惠券
        BigDecimal tmpCouponPrice = new BigDecimal(0.00);
        Integer tmpUserCouponId = 0;
        int tmpCouponLength = 0;   // 用户优惠券数量
        Integer tmpCouponId = 0;   // 优惠券的ID
        paramMap.clear();
        paramMap.put("user_id", id);
        // 状态为0，代表未使用
        paramMap.put("status", 0);
        R couponUserR = promotionFeign.couponUserList(paramMap);
        List<Map> couponUserMapList = MapUtil.get((Map) couponUserR.get("page"), "list", List.class);
        for (Map map : couponUserMapList) {

            // 根据couponUser表的coupon的ID查询优惠券详情
            R couponInfo = promotionFeign.couponInfo(MapUtil.get(map, "couponId", Integer.class));
            // 优惠券详细对象
            CouponHomeVo coupon = MapUtil.get(couponInfo, "coupon", CouponHomeVo.class);
            tmpCouponLength++;
            if (tmpCouponPrice.compareTo(coupon.getDiscount()) == -1) {
                tmpUserCouponId = MapUtil.get(map, "id", Integer.class);
                tmpCouponPrice = coupon.getDiscount();
                tmpCouponId = coupon.getId();
            }
        }
        // 获取优惠券减免金额，优惠券可用数量
        BigDecimal couponPrice = new BigDecimal(0);
        // 这里存在三种情况
        // 1. 用户不想使用优惠券，则不处理
        // 2. 用户想自动使用优惠券，则选择合适优惠券
        // 3. 用户已选择优惠券，则测试优惠券是否合适
        if (checkoutFrom.getCouponId() == null || checkoutFrom.getCouponId().equals(-1)) {
            checkoutFrom.setCouponId(-1);
            checkoutFrom.setUserCouponId(-1);
        } else if (checkoutFrom.getCouponId().equals(0)) {
            couponPrice = tmpCouponPrice;
            checkoutFrom.setCouponId(tmpCouponId);
            checkoutFrom.setUserCouponId(tmpUserCouponId);
        } else {
            R couponR = promotionFeign.couponInfo(checkoutFrom.getCouponId());
            CouponHomeVo couponVo = MapUtil.get(couponR, "coupon", CouponHomeVo.class);
            if (couponVo == null) {
                couponPrice = tmpCouponPrice;
                checkoutFrom.setCouponId(tmpCouponId);
                checkoutFrom.setUserCouponId(tmpUserCouponId);
            } else {
                couponPrice = couponVo.getDiscount();
            }
        }
        // 根据订单商品总价计算运费，满88则免运费，否则8元；
        BigDecimal freightPrice = new BigDecimal(0.00);
        if (checkedGoodsPrice.compareTo(MapUtil.get(mallFeign.getFreightLimit(), "freight_limit", BigDecimal.class)) < 0) {
            freightPrice = MapUtil.get(mallFeign.getFreight(), "freight", BigDecimal.class);
        }

        // 可以使用的其他钱，例如用户积分
        BigDecimal integralPrice = new BigDecimal(0.00);

        // 订单费用
        BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal(0.00));

        // 订单总价
        BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);


        resultMap.put("addressId", checkoutFrom.getAddressId());
        resultMap.put("couponId", checkoutFrom.getCouponId());
        resultMap.put("userCouponId", checkoutFrom.getUserCouponId());
        resultMap.put("cartId", checkoutFrom.getCartId());
        resultMap.put("grouponRulesId", checkoutFrom.getGrouponRulesId());
        resultMap.put("grouponPrice", grouponPrice); // 团购优惠
        resultMap.put("availableCouponLength", tmpCouponLength); // 可以优惠券数量
        resultMap.put("goodsTotalPrice", checkedGoodsPrice); // 商品总价
        resultMap.put("freightPrice", freightPrice); //运费价格
        resultMap.put("couponPrice", couponPrice); // 优惠券价格
        resultMap.put("orderTotalPrice", orderTotalPrice);// 订单费用
        resultMap.put("actualPrice", actualPrice);
        resultMap.put("checkedGoodsList", checkedGoodsList);// 订单所有商品
        return resultMap;

    }

    // 用户购物车
    public Map homeIndex() {
        Map<String, Object> resultMap = new HashMap<>();
        Long id = loginUserHolder.getCurrentUser().getId();
        // TODO 1、cartList   购物车详情
        // 根据id查询用户购物车商品详情
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("user_id", id);
        R cartR = orderFeign.list(paramMap);
        List<Map> cartList = (List<Map>) ((Map) cartR.get("page")).get("list");
        resultMap.put("cartList", cartList);
        // TODO 2、cartTotal   购物车总和
        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount", cartList.size());  //全选数量
        cartTotal.put("checkedGoodsCount", cartList.size());  // 选中的商品数量
        BigDecimal goodsAmount = new BigDecimal(0.00);
        for (Map map : cartList) {
            BigDecimal price = MapUtil.get(map, "price", BigDecimal.class);
            goodsAmount = goodsAmount.add(price);
        }
        cartTotal.put("goodsAmount", goodsAmount);  // 全选金额
        cartTotal.put("checkedGoodsAmount", goodsAmount);   // 选中总金额
        resultMap.put("cartTotal", cartTotal);
        return resultMap;
    }
}
